# encoding: utf-8
'''
Created: 2014-04-28 12:46

@author: VAN
'''
from HTMLParser import HTMLParser
import json
import logging
import urllib2

import BeautifulSoup

from src.crawler import util


logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s [%(lineno)d] %(levelname)s %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                filename='app.log',
                filemode='w')
logger = logging.getLogger();

class QQ(object):
    lrc_url = 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_yqq_song_detail_info.fcg?songmid=(mid)'
    
    def __init__(self, copyright_id, song_name, singer_name):
        self.uid = ''
        
        self.copyright_id = copyright_id;
        self.song_name = song_name;
        self.singer_name = singer_name;
        
        self.qq_guid = '9643858795'
        self.qq_song_id = '';
        self.qq_song_mid = '';
        self.qq_song_name = '';
        self.qq_singer_name = '';
        self.qq_lrc_url = '';
        self.qq_mp3_url = '';
        
    def __str__(self):
        return str(self.uid) + '|' + str(self.copyright_id) + '|' + self.song_name + '|' + self.singer_name + '|' + str(self.qq_song_id) + '|' + str(self.qq_song_mid) + '|' + self.qq_song_name + '|' + self.qq_singer_name + '|' + str(self.qq_lrc_url) + '|' + str(self.qq_mp3_url) 
     
    def search(self):
        search_url_format = 'http://s.plcloud.music.qq.com/fcgi-bin/smartbox.fcg?o_utf8=1&utf8=1&key={keyword}&g_tk=938407465&loginUin=0&hostUin=0&format=jsonp&inCharset=GB2312&outCharset=utf-8&notice=0&platform=yqq&jsonpCallback=MusicJsonCallback&needNewCode=0'
        search_url = search_url_format.format(keyword=urllib2.quote(self.song_name + ' ' + self.singer_name))
        req = urllib2.Request(url=search_url)
        html = urllib2.urlopen(req).read();
        #   html='MusicJsonCallBack({retcode:0, tips:{song:[{id:265242, mid:"0017FBUP3syUId", name:"信不信由你", singer_name:"张露"}],singer:[],album:[],mv:[]}});';
        extract_json_regex = 'MusicJsonCallBack\((.*)\)'
        similer_json_str = util.extractjson(html, extract_json_regex)
        print similer_json_str
        if (similer_json_str != '') :
            jo = util.similerjsonstr2dict(similer_json_str)
            if len(jo['tips']['song']) > 0:
                jsong = jo['tips']['song'][0]
                self.qq_song_id = jsong['id']
                self.qq_song_mid = jsong['mid']
                self.qq_song_name = jsong['name']
                self.qq_singer_name = jsong['singer_name']
                
    def extract_download_url(self):
        if len(self.qq_song_mid) == 0:
            return
        key_url_format = 'http://base.music.qq.com/fcgi-bin/fcg_musicexpress.fcg?json=3&guid={guid}&g_tk=938407465&loginUin=0&hostUin=0&format=jsonp&inCharset=GB2312&outCharset=GB2312&notice=0&platform=yqq&jsonpCallback=MusicJsonCallback&needNewCode=0'
        key_url = key_url_format.format(guid=self.qq_guid)
        req = urllib2.Request(url=key_url)
        rsp = urllib2.urlopen(req).read();
        regex = 'jsonCallback\((.*)\)'
        jsonstr = util.extractjson(rsp, regex)
        jobj = json.loads(jsonstr)
        print jobj
        # {"code":0,"sip":["http://ws.stream.qqmusic.qq.com/", "http://cc.stream.qqmusic.qq.com/", "http://222.211.82.25/streamoc.music.tc.qq.com/"],"key": "7C06DDBF11F4327D2D24BC72BC08C977D147640B776E04F39AD166382510DFBF"}|QQ|十年|陈奕迅|4830342|001OyHbk2MSIi4|十年|陈奕迅||
        if len(jobj['sip']) > 0:
            link_download_url_format = '{host}C200{mid}.m4a?vkey={key}&guid={guid}&fromtag=0'
            link_download_url = link_download_url_format.format(host=jobj['sip'][0], mid=self.qq_song_mid, key=jobj['key'], guid=self.qq_guid)
            self.qq_mp3_url = link_download_url
    
    def downloadfile(self):
        self.parse_lrc_content();
        util.mp3_download_handler(self.qq_mp3_url, self.copyright_id)
        
    def parse_lrc_content(self):
        if len(self.qq_song_mid) == 0:
            return
        url_index_format = 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_yqq_song_detail_info.fcg?songmid={mid}'
        url_index = url_index_format.format(mid=self.qq_song_mid);
        req = urllib2.Request(url=url_index)
        rsp = urllib2.urlopen(req).read().decode('GBK');
        soup = BeautifulSoup.BeautifulSoup(rsp)
        lrccontent = soup.find(attrs={'id':'lrc_content'})
        htm_parser = HTMLParser()
        content = htm_parser.unescape(lrccontent.string.strip())
        print content.encode('UTF-8').replace('\\n', '\n')
#         content = lrccontent.string.replace('&#58;', ':').replace('&#92;n', '\n').replace('&#46;', '.').replace('&#32;', ' ').replace('&#45;', '-');
        util.lrc2diskhandler(content.encode('UTF-8').replace('\\n', '\n'), self.copyright_id);
        
        
# qq = QQ('QQ', '十年', '陈奕迅')
# qq.search()
# qq.extract_download_url()
# qq.downloadfile()
qq = QQ('QQ', '十年', '陈奕迅')
qq.copyright_id = 1
qq.qq_song_mid = '003ZH4jK0SRiaH'
qq.extract_download_url()
qq.downloadfile()

# qq.parse_lrc_content()
 
# print qq;

